<template>
	<view>
		<view class="top-select-date">
			<view class="box" v-for="(item,index) in dateList" :key="index" @click="changeDate(index)">
				<text class="day" :class="visitedIndex == index?'visited-color':''">{{ item.day }}</text>
				<text class="date" v-if="index == 0" :class="visitedIndex == index?'visited-color':''">今</text>
				<view v-else>
					<text class="date" :class="visitedIndex == index?'visited-color':''">{{ item.date }}</text>
				</view>
			</view>
		</view>
		
		<!-- 店铺数量为1及以下的话就不显示该框 -->
		<!-- <view class="tips-positon" v-if="massageNum>1">
			<view class="tips-inbox" @tap="showModal()">
				<image class="icon" src="/static/appointment/tips.png"></image>
				<text class="tips-text">您可以点击
					<text style="color: #7EC0EE;">这里</text>
					切换不同店铺</text>
			</view>
		</view> -->
		<view>
			<scroll-view class="scroll-view_H" scroll-x="true" scroll-left="0">
						
			<view class="doctor-outbox" v-if="isGetData" v-for="(item,index) in doctorList" :key="item.doctorInfo.id">
				<view class="doctor-info" style="margin:0 auto;">
					<!-- 用户头像 -->
					<image class="doctor-icon" :src="item.doctorInfo.img" style="border-radius: 50%;height:50px;width: 50px;"></image>
					<view>
						<text class="doctor-name">{{item.doctorInfo.name}}</text>
					</view>
					<div class="gray-text">上午:</div>
						<view v-for="(innerItem,index) in item.timePeriods" :key="index">
							<div v-if="isAfternoon === index" class="gray-text">下午:</div>
							<!-- 显示名字 -->
							<!-- 自己预约看见的 -->
							<div v-if="item.residues[index] == -2 && isShowName === 1 && item.appointments[index].openId === openid" style="color: #d57878;font-size: 15px;margin:0 auto -10px;" @click="cancelSelectTimePeriod(item.appointments,index,innerItem[0],innerItem[1])">
							{{innerItem[0]}}</div>
							<view v-if="item.residues[index] == -2 && isShowName === 1 && item.appointments[index].openId === openid" class="line-Box"></view>
							<view v-if="item.residues[index] == -2 && item.appointments[index].status !== -10 && isShowName === 1 && item.appointments[index].openId === openid" style="color: #d57878;font-size: 13px;margin:0 auto;" @click="cancelSelectTimePeriod(item.appointments,index,innerItem[0],innerItem[1])">
								{{item.appointments[index].childName}}
							</view>
							<!-- 别人预约看见的 -->
							<div v-if="item.residues[index] == -2 && isShowName === 1 && item.appointments[index].openId !== openid" style="color: #b0b0b0;font-size: 15px;margin:0 auto -10px;">
							{{innerItem[0]}}</div>
							<view v-if="item.residues[index] == -2 && isShowName === 1 && item.appointments[index].openId !== openid" class="line-Box1"></view>
							<view v-if="item.residues[index] == -2 && item.appointments[index].status !== -10 && isShowName === 1 && item.appointments[index].openId !== openid" style="color: #b0b0b0;font-size: 13px;margin:0 auto;">
								{{item.appointments[index].childName}}
							</view>
							<!-- 不显示名字 -->
							<!-- 自己预约看见的 -->
							<text v-if="item.residues[index] == -2 && isShowName === 0 && item.appointments[index].openId === openid" style="color: #d57878;font-size: 25px;" @click="cancelSelectTimePeriod(item.appointments,index,innerItem[0],innerItem[1])">{{innerItem[0]}}</text>
							<!-- 别人预约看见的-->
							<text v-if="item.residues[index] == -2 && isShowName === 0 && item.appointments[index].openId !== openid" style="color: #b0b0b0;font-size: 25px;">{{innerItem[0]}}</text>
							<!-- 0代表该师傅今天已被预约完 -1代表过了预约时间 -->
							<text v-if="item.residues[index] == 0 || item.residues[index] == -1" style="color: #b0b0b0;font-size: 25px;">{{innerItem[0]}}</text>
							<!-- 大于0代表可以预约 -->
							<text v-if="item.residues[index] > 0" style="color: #7EC0EE;font-size: 25px;" @click="selectTimePeriod(item.doctorInfo.id,innerItem[0],innerItem[1],index,item.planId)">{{innerItem[0]}}</text>
						</view>
				</view>
			</view>
			
			</scroll-view>
					
		</view>
		<!-- 当没有医生出诊信息时 -->
		<noDataPage :message='message' v-if="!isGetData"></noDataPage>

		<!-- 从底部弹出选择 -->
		<view class="cu-modal bottom-modal" :class="isShowModal?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-green" @click="insureChangeMassage()">确定</view>
					<view class="action text-blue" @tap="hideModal()">取消</view>
				</view>
				<view class="bottom-massage-box">
					<view class="massage-box" v-for="(item,index) in massageList" :key="item.id">
						<view class="massage" :class="showVisited == item.id?
						 'visited-background':'invisited-background'" @click="changeMassage(item.id, item.name)">
							<text class="text">
								{{ item.name }}
							</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 弹出框结束 -->
	</view>
</template>

<script>
	import { errors } from '@/common/js/errorTips.js'
	import {formDate} from '@/common/js/formDate.js';
	import {getOutCall} from '@/common/api/outCall.js';
	import {getDoctorInfoById} from '@/common/api/doctor.js';
	import {getAllDoctor} from '@/common/api/doctor.js';
	import {getAllMassage} from '@/common/api/massage.js';
	import {getMassageVisitPlan} from '@/common/api/doctor.js'
	import {addAppoint,cancelAppoint} from '@/common/api/appoint.js'
	import {getConfig, getWeekAndConfig} from '@/common/api/config.js'
import { getToken } from '../../../../common/utils/auth';
	var _self = 1,timer = null;
	export default {
		data() {
			return {
				//是否放票
				isRelease:'',
				week:'',//只渲染到week，因为只放票到week
				indexs:'',
				isAfternoon:'',
				isRefresh:false,
				// 获取openid
				openid: uni.getStorageSync("openid"),
				count:'',
				isShowName: 0,//时间段是否显示名字 0 不显示 1 显示
				date: '',//记录当前日期
				massageId:0,//记录当前店铺id
				massageNum:0,//记录店铺数量
				isShowMoreDate: true,
				visitedIndex: 0, // 用来表示当前点击的index是哪个
				dateList: [],
				isShowModal: false,
				massageList: [],
				visitedMassage: 0,
				showVisited: 0,
				showName: '',
				doctorList: [], // 获取的医生出诊列表
				sentDate: '', // 用于传给后台的时间日期
				iconURL: '/static/appointment/',
				isGetData: false, // 没有医生出诊信息时为false
				message: '师傅出诊', 
				massageData: {}, // 用于获取店铺id，专科门诊id,日期
				timePeriod: []    ,// 存储时间段
			}
		},
		methods: {
			// 获取配置
			// 是否时间段下面显示名字
			getConfig(day){
				let that = this
				getWeekAndConfig(day).then(res =>{
					if(res.data.code === 200){
						//是否显示
						res.data.data.isShow === "1" ? (that.isShowName = 1) : (that.isShowName = 0)
						//每人预约的数量
						that.count = res.data.data.count
						//放票数量
						that.isRelease = res.data.data.action
						//获取week
						that.week = res.data.data.week
						
						that.indexs = that.getSubsript(that.numToWordDay(that.week),that.dateList);
					}
				})
			},
			// 下拉刷新
			onPullDownRefresh() {
				this.loadingText = '加载中'
				let _self = this
				if (timer != null) {
					clearTimeout(timer);
				}
				timer = setTimeout(function() {
					if(_self.loadingText!='已加载全部'){
						_self.isRefresh = true
						_self.changeDate(_self.visitedIndex)
						uni.stopPullDownRefresh();
					}
				}, 1000);
			},
			// // 获取access_token
			// access_token() {
			// 	   return uni.request({
			// 	       method: 'get',
			// 	       url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`,
			// 	       dataType: 'json',
			// 	       timeout: 30000
			// 	   }).then(res => {
			// 	       let [err, success] = res
			// 	       if (success.statusCode == 200) {
			// 	           return success.data.access_token
			// 	       }
			// 	   })
			// },

			// 选择时间段预约
			selectTimePeriod: function(id,time1,time2,index,planId){
				console.log("开始预约,token为:",getToken())
				let that = this
				let timePeriod = time1 + '-' + time2;
				// console.log(getToken())
				// console.log("Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJvX2ZjbTQ5M2tneHlYMjVneTdVM21JYkg1aE1nIiwiY3JlYXRlZCI6MTY4OTk5ODQyNTEzMywiZXhwIjoxNjkwNjAzMjY5fQ.XKCWKGuLn8nWJXxe90wQucVVmmPenLnLfdHf0tbbQcu6iPQm4AWDRchb2vCaWMHmjJT62K6gRGe9JbKdkzv60g:wx")
				// this.openid = "o_fcm493kgxyX25gy7U3mIbH5hMg"
				uni.showModal({
				    title: '提示',
				    content: '确定预约'+timePeriod+'时间段嘛',
				    success: function (res) {
				        if (res.confirm) {
							// if(uni.getStorageSync("isAppointment") === true){
							// 	uni.showToast({
							// 		title: 'me',
							// 		icon: 'danger'
							// 	})
							// }
				            //console.log('用户点击确定');
							let data = {
								day: that.massageData.date,
								doctorId: id,
								planId: planId,
								timePeriod:index+1,
							}
							addAppoint(data,that.count,that.massageData.massageId).then(res => {
									//预约成功后刷新页面
									that.getAllDoctor(that.massageData.massageId,that.massageData.date);
									uni.showToast({
										title: '预约成功',
										icon: 'success'
									})
								
								//uni.setStorageSync("isAppointment",true)
								//预约成功弹出发送订阅消息授权框
								// wx.requestSubscribeMessage({
								//   tmplIds: ['vExe61vh1zp6B4f-95hJZoTx5k8KTXnCrwCLdkgIgNw'],
								//   success:(res)=> {
								// 	  console.log('res',res);
								// 		that.notice()
								//   },
								//   fail(){
								// 	 uni.showToast({
								// 	 	title: '订阅消息失败',
								// 	 	icon: 'error'
								// 	 })
								//   }
								// });
								//刷新页面
								//localtion.reload()
							}).catch(e =>{
								that.changeDate(that.visitedIndex)
								//console.log("eeeeeeeeeeeee",e.data.message)
								if(e.data.message === "已经被预约了"){
									uni.showToast({
										title: '该时间段已有人预约',
										icon: 'error'
									})
								}else if(e.data.message === "今天的预约次数已经超过了"+that.count+"次"){
									uni.showToast({
										title: '只能预约'+that.count+'次哦!',
										icon: 'error'
									})
								}else if(e.data.message === "医生不存在"){
									uni.showToast({
										title: '医生不存在',
										icon: 'error'
									})
								}else if(e.data.message === "时间段不存在"){
									uni.showToast({
										title: '时间段不存在',
										icon: 'error'
									})
								}else{
									uni.showToast({
										title: '预约失败请刷新!',
										icon: 'error'
									})
								}
								
								
							})
				        } 
				    }
				});
			},
			// notice() {
			// 		let self = this
			// 		//下方的thing1，thing2和其他，对应的是你选取模板的模板详情中的字段名称(可在小程序后台模板查看对应的字段，要和上面的字段一样)，需要更改成你自己的
			// 		const pushmsg = {
			// 			"touser": "ou5OT5Jo8_tp5JhxGzxxx1dt_6ys",
			// 			"template_id": "vExe61vh1zp6B4f-95hJZoTx5k8KTXnCrwCLdkgIgNw",
			// 			"data": {
			// 				"thing9": {
			// 					"value": "严飞"
			// 				},
			// 				"phone_number13": {
			// 					"value": "15984475985"
			// 				},
			// 				"thing2": {
			// 					"value": "万达店"
			// 				},
			// 				"character_string10": {
			// 					"value": "08:40-09:20"
			// 				},
			// 			}
			// 		}
			// 		uni.request({
			// 			// 此处的mytoken
			// 			url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=68_dqWPhmoBCo63XT-WTxWZwkJYCs44xlIGYGWgZIDm2_RI6ufGm-gAlYbGnTKQh7xHq7BJIhpWpFvJmJaW1GDpeS56TrQo-H9rwvIx7Ji8tX6iLhmAB6m3teCrnvwLUSgAFATCA',
			// 			data: JSON.stringify(pushmsg),
			// 			method: 'POST',
			// 			success: function(res) {
			// 				console.log('success',res);
			// 			}
			// 		})
			// },
			// 取消预约
			cancelSelectTimePeriod: function(appointments,indexs,time1,time2){
				console.log('time1',time1)
				let timePeriod = time1 + '-' + time2;
				let id = 0;
				let that = this;
				//console.log(appointments)
				let appointment = appointments
				appointment.forEach(function(item){
					if(item.timePeriod === indexs + 1){
						id = item.id
					}
				})
				uni.showModal({
				    title: '提示',
				    content: '确定取消预约'+timePeriod+'时间段嘛',
				    success: function (res) {
				        if (res.confirm) {
							cancelAppoint(id).then(res => {
								//console.log('取消成功')
								//取消预约成功后刷新页面
								that.getAllDoctor(that.massageData.massageId,that.massageData.date);
								uni.showToast({
									title: '取消成功',
									icon: 'success'
								})
							}).catch(() => {
								uni.showToast({
									title: '取消失败',
									icon: 'danger'
								});
							})
				        }
				    }
				});
				
			},
			// 分割时间段
			formatTimePeriod: function(item){
				this.timePeriod = []
				let arr = item.split(',')
				let that = this
				arr.forEach(function(item,index){
					that.timePeriod.push(item.split('-'))
				})
				//console.log('that.timePeriod',that.timePeriod)
				return that.timePeriod;
				
			},
			// 获取今天的日期
			getCurrentDate: function() {
				let currentDate = new Date()
				this.dateList = formDate(currentDate, 'week-date');
				//将今天日期存入
				uni.setStorageSync('currentDate',formDate(currentDate,'YYYY-MM-DD'));
			},
			// 切换日期
			changeDate: function(index) {
				this.getConfig(this.date)
				this.isRefresh = false
				this.visitedIndex = index
				//大于index且设置放票就不放号
				if(index > this.indexs && this.isRelease === 1){
					this.doctorList = []
					this.isGetData = false
					return;
				}
				let date = this.dateList[index].year + '-' + this.dateList[index].month + 
				'-' + this.dateList[index].date;
				this.massageData.date = date;
				//点击改变日期之后将改变的日期存入
				uni.setStorageSync('currentDate',date);
				this.getAllDoctor(this.massageData.massageId,date)
			},
			// 打开模态框
			showModal: function() {
				this.isShowModal = true
			},
			// 关闭模态框
			hideModal: function() {
				this.isShowModal = false
				this.showVisited = this.visitedMassage
			},
			// 切换店铺信息
			changeMassage:function(id, name) { 
				this.showVisited = id;
				this.showName = name
			},
			// 点击确定确认切换店铺
			insureChangeMassage:function() {
				this.visitedMassage = this.showVisited
				this.isShowModal = false
				// 获取切换的店铺的出诊信息
				//console.log(this.visitedMassage)
				this.getAllDoctor(this.visitedMassage,this.date)
				let massage = {
					id: this.visitedMassage,
					name: this.showName
				}
				uni.setStorageSync('massage', JSON.stringify(massage))
			},
			//获取渲染到星期几的下标
			getSubsript:function(week,dateList){
				let indexs = '';
				dateList.forEach(function(item,index){
					if(week === item.day){
						indexs = index;
					}
				})
				return indexs;
			},
			numToWordDay(day) {
				switch (day) {
					case 1:
						return '一';
						break;
					case 2:
						return '二';
						break;
					case 3:
						return '三';
						break;
					case 4:
						return '四';
						break;
					case 5:
						return '五';
						break;
					case 6:
						return '六';
						break;
					case 7:
						return '日';
						break;
				}
			},
			//获取该店铺当天所有医生出诊情况
			getAllDoctor: function(massageId, today) {
				this.doctorList = [];
				if(!this.isRefresh){
					uni.showLoading({
						title: '加载中'
					})
				}else{
					uni.showToast({
						title: '刷新成功',
						icon: 'success'
					})
				}
				getAllDoctor(massageId, today).then(res =>{
					if(res.data.code === 200) {
						const data = res.data.data.doctorlist;
						let that = this;
						if(data.length === 0 || data === null) {
							this.isGetData = false
							//console.log(this.isGetData)
						} else {
							this.isGetData = true
							that.doctorList = []
							data.forEach(function(item, index){
								let doctorInfo = {
									id:item.id,
									name:item.name,
									img:item.img,
									duan:item.duan
								}
								let residues = []
								let planId = 0
								let appointments = []
								let timePeriods = []
								let arr = []
								residues = item.visitPlanResiduesDTOS.residues
								planId = item.visitPlanResiduesDTOS.planId
								arr = item.visitPlanResiduesDTOS.appointments
								for(let i=0,j=0;i<residues.length;i++){
									if(arr.length === 0 || arr === []){
										appointments.push({
											status: -10
										})
									}
									else if( j < arr.length && i === arr[j].timePeriod-1){
										appointments.push(arr[j])
										j++;
									}else{
										appointments.push({
											status: -10
										})
									}
								}
								timePeriods = that.formatTimePeriod(doctorInfo.duan)
								console.log(doctorInfo.name)
								that.doctorList.push({
									doctorInfo: doctorInfo,
									residues: residues,
									planId: planId,
									appointments:appointments,
									timePeriods:timePeriods
								})
								//遍历判断好久是下午
								if(that.isAfternoon === ''){
									timePeriods.forEach(function(item,index){
										let num = item[1].split(':') //取第二个时间段,并通过':'分割,获取整点时间判断是否为下午
										if(parseInt(num[0]) < 14){
											that.isAfternoon = index + 1
											// console.log('num',parseInt(num[0]))
											// console.log('index',index)
										}
									})
								}
								console.log("doctorList",that.doctorList)
							})
							
						}
						
					}
				}).catch((e) => {
					console.log(e)
					if(!this.isRefresh){
						uni.hideLoading()
					}
					errors('获取预约列表信息失败')
				})
				if(!this.isRefresh){
					uni.hideLoading()
				}
			}
		},
		onLoad(e) {
			this.isRefresh = false
			this.getCurrentDate()
			let today;
			if(uni.getStorageSync('dateInfo')) {
				let date = JSON.parse(uni.getStorageSync('dateInfo'));
				 today = date.dateInfo.year + '-' + date.dateInfo.month + '-' 
				+ date.dateInfo.date;
				this.visitedIndex = date.index
			} else {
				// 获取当天日期
				 today = this.dateList[0].year + '-' + this.dateList[0].month + '-' + this.dateList[0].date;
			}
			//this.getOutCall(today, e.massageId, e.departmentId, e.outpatientId);
			this.date = today
			//获取该店铺当天所有医生出诊情况
			this.showVisited = e.massageId;
			this.visitedMassage = this.showVisited
			this.massageData = {
				massageId: e.massageId,
				departmentId: e.departmentId,
				outpatientId: e.outpatientId,
				date: today
			}
			this.getConfig(this.massageData.date)
			this.getAllDoctor(e.massageId, today);
			uni.removeStorageSync('dateInfo')
			//console.log(uni.getStorageSync('doctor'))
		},
		onShow() {
			// 获取店铺信息
			getAllMassage(1, 50).then(res => {
				if (res.data.code === 200) {
					this.massageList = res.data.data.list
					//获取店铺数量，如果店铺数量小于等于1，则不显示切换店铺
					this.massageNum = res.data.data.total
				}
			}).catch(() => {
				errors('网络')
			})
		}
	}
</script>

<style lang="scss">
	@import '@/common/scss/doctor.scss';
	@import '@/common/scss/common.scss';
	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}
	.scroll-view-item_H {
		display: inline-block;
		width: 100px;
		height: 1300rpx;
		line-height: 1300rpx;
		text-align: center;
		font-size: 36rpx;
		}
	// 顶部选择日期
	.top-select-date {
		width: 100%;
		height: 120rpx;
		@include flex-direction(row);
		align-items: center;
		border-bottom: 1px solid $border-color;

		.box {
			width: 25%;
			height: 85%;
			@include flex-direction(column);
			text-align: center;
			align-items: center;

			.date .day .icon {
				width: 100%;
				height: 50%;
				display: flex;
			}

			.day {
				align-items: flex-start;
				@include font-style(16px, 500, $gray-color);
			}

			.date {
				align-items: flex-end;
				@include font-style(16px, 500, #000000);
			}

			.icon {
				@include icon-size(50rpx, 50rpx);
			}
		}

		.box:not(:last-child) {
			border-right: 1px solid $border-color;
		}
	}

	.tips-positon {
		margin-top: 30rpx;
		@extend .tips-box;
		margin-bottom: 10rpx;
	}

	.doctor-job-box {
		width: 100%;
		height: 50%;
		@include flex-direction(row);
		align-items: center;
	}
	.doctor-name {
		width: 50%;
		@include font-style(20px, bold, #000000);
		vertical-align: middle;
	}
	.gray-text {
		width: 100%;
		height: 50%;
		@include font-style(17px, 500, $gray-color);
		display: flex;
		align-items: center;
	}
	//下划线
	.line-Box {
		background-color: #d57878;
		width: 80%;
		height: 3rpx;
		margin-top: 10rpx;
		margin-right: 15rpx;
	}
	.line-Box1 {
		background-color: #b0b0b0;
		width: 80%;
		height: 3rpx;
		margin-top: 10rpx;
		margin-right: 15rpx;
	}
	// 从底部弹出不同分院的选择
	.bottom-massage-box {
		width: 100%;
		height: 100%;
		background: #FFFFFF;
		display: flex;
		flex-wrap: wrap;

		.massage-box {
			width: 33%;
			height: 80rpx;
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
			.massage {
				@include width-margin(85%, 85%);
				border-radius: 10px;
				text-align: center;
				display: table;
				.text{
					width: 100%;
					height: 100%;
					@include font-style(16px, 500, #FFFFFF);
					display: table-cell;
					vertical-align: middle;
				}
			}
			.visited-background{
				background: $major-color;
			}
			.invisited-background{
				background: #D1D1D1;
			}
		}
	}
</style>
